<template>
  <el-dialog
    :title="!dataForm.id ? '新增设计师' : '修改设计师'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-row>
        <el-col :span="15">
          <el-form-item label="头像" prop="avatar">
            <my-upload field="img"
                       @crop-success="cropSuccess"
                       @crop-upload-success="cropUploadSuccess"
                       @crop-upload-fail="cropUploadFail"
                       v-model="show"
                       :url="config.uploaddDesignerHeader"
                       :params="params"
                       :headers="headers"
                       img-format="png">
            </my-upload>
            <div class="myhead">
              <el-tooltip content="点击更改头像" placement="top">
                <img :src=dataForm.avatar class="img-responsive img-circle center-block" @click="toggleShow">
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="昵称" prop="nickname" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.nickname"  placeholder="昵称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="手机号" prop="mobile" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="邮箱" prop="email" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="介绍" prop="introduce">
            <el-input type="textarea"
                      :autosize="{ minRows: 3, maxRows: 5}"
                      placeholder="设计师介绍"
                      v-model="dataForm.introduce">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dataForm.id === 0">
        <el-col :span="15">
          <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="dataForm.id === 0">
        <el-col :span="15">
          <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
            <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import 'babel-polyfill'
  import myUpload from 'vue-image-crop-upload'
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        show: false,
        params: {
          token: this.$cookie.get('token'),
          name: 'avatar'
        },
        headers: {
          smail: '*_~'
        },
        imgDataUrl: '',
        visible: false,
        roleList: [],
        dataForm: {
          id: 0,
          username: '',
          nickname: '',
          introduce: '',
          avatar: 'http://file-cdn-theme.cykonhy.com/default/avatar.jpg',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          userType: '2',
          roleIdList: [3],
          status: 1
        },
        dataRule: {
          nickname: [
            { required: true, message: '用户昵称', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          introduce: [
            { required: true, message: '设计师介绍', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
        }
      }
    },
    components: {
      'my-upload': myUpload
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/theme/designer/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.useruame = data.designer.username
                this.dataForm.nickname = data.designer.nickname
                this.dataForm.userType = data.designer.userType
                this.dataForm.introduce = data.designer.introduce
                this.dataForm.salt = data.designer.salt
                this.dataForm.email = data.designer.email
                this.dataForm.mobile = data.designer.mobile
                this.dataForm.roleIdList = data.designer.roleIdList
                this.dataForm.status = data.designer.status
                this.dataForm.avatar = data.designer.avatar
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/theme/designer/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.id || undefined,
                'username': this.dataForm.mobile,
                'nickname': this.dataForm.nickname,
                'introduce': this.dataForm.introduce,
                'userType': this.dataForm.userType,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'roleIdList': this.dataForm.roleIdList,
                'avatar': this.dataForm.avatar,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      toggleShow () {
        this.show = !this.show
      },
      /**
       * crop success
       * [param] imgDataUrl
       * [param] field
       */
      cropSuccess (imgDataUrl, field) {
        //console.log('-------- crop success --------')
        this.imgDataUrl = imgDataUrl
      },
      /**
       * upload success
       *
       * [param] jsonData   服务器返回数据，已进行json转码
       * [param] field
       */
      cropUploadSuccess (jsonData, field) {
        //console.log('-------- upload success --------')
        //console.log(jsonData)
        //console.log('field: ' + field)
        if (jsonData.code != 0) {
          this.$message({
            message: jsonData.msg,
            type: 'error',
            duration: 3000,
            onClose: () => {
              this.visible = false
            }
          })
        }
        this.imgDataUrl = jsonData.filePath
        this.dataForm.avatar = jsonData.filePath
      },
      /**
       * upload fail
       *
       * [param] status    server api return error status, like 500
       * [param] field
       */
      cropUploadFail (status, field) {
        //console.log('-------- upload fail --------')
        console.log(status)
        console.log('field: ' + field)
      }
    }
  }
</script>
<style>
  .myhead {
    margin: 0 auto;
    text-align: center;
    cursor: pointer;
  }
  .myhead img {
    width: 100px;
    height: 100px;
    position: relative;
  }
  .center-block {
    display: block;
    margin-right: auto;
    margin-left: auto;
  }
  .img-circle {
    border-radius: 50%;
  }
  .carousel-inner>.item>a>img, .carousel-inner>.item>img, .img-responsive, .thumbnail>img, .thumbnail a>img {
    display: block;
    max-width: 100%;
    height: auto;
  }
  img {
    vertical-align: middle;
  }
</style>
